package com.ifcar.app.activity;

import java.io.File;
import java.io.IOException;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.util.FileUtils;
import com.ifcar.app.util.NeteaseHttpClient;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.util.ThemeSettingsHelper.ThemeCallback;
import com.ifcar.app.activity.R;

public class SettingsActivity extends PreferenceActivity implements ThemeCallback{

//	private static final String CHANGE_SKIN_KEY = "changeskin";
	public static final String DOWN_PIC_KEY = "downpic";
	public static final String OFFLINE_READ_KEY = "autodownload";
	public static final String CACHE_KEY = "cache";
	private static final String ACCOUNT_KEY = "account";
	private static final String AUTOPOST_KEY = "autopost";
	private static final String NEWGUIDE_KEY = "newguide";
	private static final String LEFTRIGHTCTRL = "leftrightctrl";
	private static final String SCREENCTRL = "screenctrl";
	private static final String ABOUT_KEY = "about";
	private static final String FEED_KEY = "feedback";
	private static final String MOREAPP_KEY = "moreapp";
    private static final String CHECKUPDATE_KEY = "checkupdate";
	private SharedPreferences sp;
	private MyApplication appdata;
	
	//换肤
//	private PreferenceScreen skinPre;
	private ProgressDialog progressDialog;
	public static final String PARAM_THEME = "param_theme";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    requestWindowFeature(Window.FEATURE_NO_TITLE);
//		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
//		this.setTheme(R.style.setting_style);
		super.onCreate(savedInstanceState);
	    mThemeSettingsHelper = ThemeSettingsHelper.getThemeSettingsHelper(this);
	    mThemeSettingsHelper.registerThemeCallback(this, null);
		
	    
		setContentView(R.layout.settings);
		View v = findViewById(R.id.top_id_image);
        if (v != null) {
            v.setVisibility(View.GONE);
        }
		
		addPreferencesFromResource(R.xml.setting);
		
		TextView title = (TextView)findViewById(R.id.top_main_text);
		title.setText(R.string.menu_setting);
		
		appdata = (MyApplication)this.getApplication();
		
		sp = PreferenceManager.getDefaultSharedPreferences(this);
		
		new Thread() {
			public void run() {
				try {
					File f = new File(FileUtils.FileTempDir); 
					File f2 = new File(PicUtil.phototempDir);
					if(FileUtils.isSDCardMounted() || FileUtils.isSDCardMountedReadOnly()) {		
						 long size = (long)FileUtils.getFileSize(f) + (long)FileUtils.getFileSize(f2)+(long)FileUtils.getFileSize(SettingsActivity.this.getCacheDir());
						 Message msg = new Message();
						 msg.what = 2;
						 msg.obj = size;
						 handler.sendMessage(msg);
					}else{
						 Message msg = new Message();
						 msg.what = 2;
						 msg.obj = 0;
						 handler.sendMessage(msg);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
		
		setMenu();
		
		progressDialog = new ProgressDialog(SettingsActivity.this);
	}
	
	
	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		
		
		
		String key = preference.getKey();
		
		if(null!=key){
			
			if(key.equals(ACCOUNT_KEY)){
				
				Intent intent = new Intent(SettingsActivity.this, AccountSettingActivity.class);
				SettingsActivity.this.startActivity(intent);

			}/*else if(key.equals(CHANGE_SKIN_KEY)){
				Intent i = new Intent(SettingsActivity.this, SkinSettingActivity.class);
				startActivity(i);
			} */else if(key.equals(CACHE_KEY)) {
			    
			    new AlertDialog.Builder(this).setTitle("").setMessage("确定要清除缓存吗？")
			    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int j) {
                        
                        progressDialog.setMessage(SettingsActivity.this.getResources().getString(R.string.cleaning_cache));
                        progressDialog.setCancelable(false); 
                        progressDialog.show();
                        
                        new Thread() {
                            public void run() {
                                
                                File f = new File(FileUtils.FileTempDir); 
                                File f2 = new File(PicUtil.phototempDir);
                                try {
                                    NeteaseHttpClient.getCache(SettingsActivity.this).delete();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                if(FileUtils.deleteFile(f) && FileUtils.deleteFile(f2)) {
                                    handler.sendEmptyMessage(0);

                                } else {
                                    handler.sendEmptyMessage(1);

                                }   
                            }
                        }.start();
                    }
                }).setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(
                            DialogInterface diagloginterface, int i) {
                        // return false;
                        
                    }
                }).show();
			    
				
			
			
			}else if(key.equals(AUTOPOST_KEY)){
				
			}else if(key.equals(NEWGUIDE_KEY)){
			    sp.edit().putBoolean("newsreaderguide", true).commit();
			    sp.edit().putBoolean("detailpageguide", true).commit();
			    MyApplication a = (MyApplication) SettingsActivity.this.getApplicationContext();
	            a.setGoHome("Y");
	            menuWindow.dismiss();
	            menu_display = false;
	            Intent i = new Intent();
	            i.setClass(SettingsActivity.this, HomePage.class);
	            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            startActivity(i);
			}else if(key.equals(ABOUT_KEY)){
			    Intent intent = new Intent(SettingsActivity.this, AboutInfo.class);
			    startActivity(intent);
			}else if(key.equals(FEED_KEY)){
               
            }else if(key.equals(MOREAPP_KEY)){
               
            }else if(key.equals(CHECKUPDATE_KEY)){
                boolean isAvailable = Tools.CheckNetwork(SettingsActivity.this);
                if(isAvailable){
                    Intent intent = new Intent();
                    intent.setClass(SettingsActivity.this, DialogActivity.class);
                    startActivity(intent);
                }else{
                    Toast.makeText(SettingsActivity.this, "网络不可用", Toast.LENGTH_SHORT).show();
                }
            }else{
				
			    
			}
		
		}

		return false;

	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what) {
			case 0:
				Preference p = findPreference(CACHE_KEY);
				p.setSummary(getString(R.string.clean_cache_desc)
                        +",当前缓存大小为0K");
		
				progressDialog.dismiss();
				sp.edit().putString("cover", "").commit();
                sp.edit().putString("cover_start", "").commit();
                sp.edit().putString("cover_end", "").commit();
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                        Uri.parse("file://"
                                + Environment.getExternalStorageDirectory())));
				Toast.makeText(SettingsActivity.this, 
						SettingsActivity.this.getResources().getString(R.string.clean_success), Toast.LENGTH_SHORT).show();
				break;
			case 1:
				progressDialog.dismiss();
				Toast.makeText(SettingsActivity.this, 
						SettingsActivity.this.getResources().getString(R.string.clean_failed), Toast.LENGTH_SHORT).show();
				break;
			case 2:
				p = findPreference(CACHE_KEY);
				try {
					if(FileUtils.isSDCardMounted() || FileUtils.isSDCardMountedReadOnly()) {	
					    p.setSummary(getString(R.string.clean_cache_desc)+",当前缓存大小"
                                +FileUtils.FormetFileSize(Long.parseLong(msg.obj.toString())));
					    
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			}
		}
		
	};
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
        super.onResume();
        mPaused = false;
        if (mThemeChanged) {
            mThemeChanged = false;
            onApplyTheme();
        }

	}
	
	private PopupWindow menuWindow;
	private boolean menu_display = false;
	private LinearLayout menu_defaule;
	
	private View menu_2;
	
	private void setMenu() {
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.other_page_menu, null);			
		menuWindow = new PopupWindow(layout,LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); //后两个参数是width和height
		
		menuWindow.setAnimationStyle(R.style.menuPopupAnimation);
		menu_2 = layout.findViewById(R.id.menu_tabrow_1);
		menu_defaule = (LinearLayout)layout.findViewById(R.id.menu_default);
		menu_defaule.setVisibility(View.VISIBLE);
		
		menu_defaule.setOnClickListener(menuDefaultListener);
	}

	@Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        menu_display = false;
    }
	
	/** 系统菜单定义 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getRepeatCount()>1){
			return super.onKeyDown(keyCode, event);
		}
		if(menu_display){
			menuWindow.dismiss();
			menu_display = false;
			return true;
		}
		if(keyCode == KeyEvent.KEYCODE_MENU){
			View parent = (View)SettingsActivity.this.getListView().getParent();
			if(!menuWindow.isShowing()){
				menuWindow.showAtLocation(parent, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
				menu_display = true;
			}else{
				//如果当前已经为显示状态，则隐藏起来
				menuWindow.dismiss();
				menu_display = false;
			}
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	public void goBackClick(View view){
		finish();
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(menuWindow.isShowing()){ // 点击屏幕时，隐藏菜单
			menuWindow.dismiss();
			menu_display = false;
		}
		boolean result = false;
		try {
			result = super.dispatchTouchEvent(ev);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 默认
	 */	
	private View.OnClickListener menuDefaultListener = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			menuWindow.dismiss();
			menu_display = false;
			Editor e = sp.edit();
			e.putBoolean(OFFLINE_READ_KEY, false);
			e.putBoolean(AUTOPOST_KEY, true);
			e.putBoolean(SCREENCTRL, false);
			e.putBoolean(LEFTRIGHTCTRL, true);
			e.putBoolean(DOWN_PIC_KEY, false);
			e.commit();			
			((CheckBoxPreference)findPreference(AUTOPOST_KEY)).setChecked(true);
			((CheckBoxPreference)findPreference(SCREENCTRL)).setChecked(false);
			((CheckBoxPreference)findPreference(LEFTRIGHTCTRL)).setChecked(true);
			((CheckBoxPreference)findPreference(OFFLINE_READ_KEY)).setChecked(false);
			((CheckBoxPreference)findPreference(DOWN_PIC_KEY)).setChecked(false);
			
			Toast.makeText(SettingsActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
						
		}
	};
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
	    if(null!=progressDialog&&progressDialog.isShowing()){
	        progressDialog.dismiss();
        }
		super.onDestroy();

		mThemeSettingsHelper.unRegisterThemeCallback(this);
		if (menuWindow != null && menuWindow.isShowing()) {
            menuWindow.dismiss();
        }
		
	}
	
	private ThemeSettingsHelper mThemeSettingsHelper;
    private boolean mPaused = true;
    private boolean mThemeChanged;
    
    public void applyTheme() {
        if (mPaused) {
            mThemeChanged = true;
        } else {
            onApplyTheme();
        }
    }
    
    public ThemeSettingsHelper getThemeSettingsHelper() {
        return mThemeSettingsHelper;
    }
    
    /**
     * 重写此方法,在主题切换时调用
     */
    public void onApplyTheme() {
        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        themeSettingsHelper.setTextViewColor(this, R.id.top_main_text, R.color.main_title_color);
        themeSettingsHelper.setImageViewSrc(this, R.id.top_id_image, R.drawable.netease_top);
        themeSettingsHelper.setViewBackgroud(this, R.id.top_main_bottom, R.drawable.top_background);
        themeSettingsHelper.setViewBackgroudColor(this, R.id.setting_layout, R.color.main_bg_color);
        themeSettingsHelper.setListViewDivider(this, getListView(), R.drawable.list_divider_line);
        getListView().requestLayout();
        
        // 菜单夜间模式
        themeSettingsHelper.setViewBackgroudColor(this, menu_2, R.color.menu_layout_bg_color);
        themeSettingsHelper.setViewBackgroud(this, menu_defaule, R.drawable.menu_background);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_defaule.getChildAt(1), R.color.menu_text_color);
        //返回夜间模式
        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_common_btn, R.drawable.go_back);
    }
    
    @Override
    public Context getContext() {
        return this;
    }
}
